package com.pek.security;

import com.alibaba.fastjson2.JSONObject;
import com.pek.config.Validate;
import com.pek.control.entity.UserEntity;
import com.pek.control.util.RedisUtil;
import com.pek.util.Constants;
import com.pek.util.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    public RestResult<String> login(UserEntity loginUser) {
        UsernamePasswordAuthenticationToken authorToken = new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authorToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }
        var user = ((LoginUser) authenticate.getPrincipal()).getUserEntity();
        String token = Constants.spawnToken(user, redisUtil);
        JSONObject redisObj = new JSONObject();
        redisObj.put("ip", Validate.getIp());
        redisObj.put("id", user.getId());
        redisObj.put("time", System.currentTimeMillis());
        redisObj.put("user", authenticate.getPrincipal());
        redisUtil.set(token, redisObj, 60 * 60 * 24);
        return RestResult.success(token);
    }
}
